<?php
/*********************************************************************
 * TOWN CLASS FILE
 * 
 * Author: hthieu1110
 * Date: 18/04/2011
 **********************************************************************/
require_once dirname(realpath(__FILE__)).'./../config/config.inc.php';

class Town {
  private $townCode;
  private $Db;
  
  public function __construct($townCode) {
    try {
      $this->Db = new Db();
    } catch(Exception $e) {
      throw new Exception('<br/>File : <b>'.__FILE__.'</b><br/>Line : <b>'.__LINE__.'</b><br/>Error : '.$e->getMessage());
    }
    
    $this->townCode = $townCode;
  }

# get name -------------------------------------------------------------  
  public function getName() {
    $query = sprintf("SELECT name FROM town WHERE code='%s' LIMIT 1",
                    mysql_escape_string($this->townCode));

    $town = $this->Db->select($query);
    
    return $town['name'];
  }
  
# check if the input is valid town or not? ------------------------------
  public static function isTown($town) {
    try {
      $Db = new Db();
    } catch(Exception $e) {
      throw new Exception('<br/>File : <b>'.__FILE__.'</b><br/>Line : <b>'.__LINE__.'</b><br/>Error : '.$e->getMessage());
    }
    
    preg_match('/(.+)\((.+)\)/', $town, $townMatched);
    
    if (empty($townMatched)) return false;
    
    $townName = trim(htmlspecialchars($townMatched[1], ENT_QUOTES));
    $townCode = trim($townMatched[2]);
    
    $query = sprintf("SELECT id FROM town WHERE code='%s' AND name='%s' LIMIT 1",
                    mysql_escape_string($townCode),
                    mysql_escape_string($townName));

    $town = $Db->select($query);
 
    if(empty($town)) return false;

    return $town['id'];
  }
}